package com.tian.user.security;

import com.tian.user.exception.AuthenticationEntryPointException;
import com.tian.user.exception.AccessDeniendHandlerException;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

/**
 * @author zhumengping
 * @title: ResourceServerConfig
 * @projectName zhump-cloud
 * @date 2023/8/4 11:21
 */
@Log4j2
@Configuration
@EnableResourceServer
//让权限注解生效@PreAuthorize
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {


    final String RESOURCE_ID = "user-resource";


    @Autowired
    private IResourceServerTokenServices tokenServices;


    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(RESOURCE_ID).tokenServices(tokenServices).stateless(true);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        log.info("[ResourceServerConfig-configure()]:HttpSecurity");
        http.cors().and()
                .authorizeRequests()
                .and()
                .csrf()
                .disable()
                .exceptionHandling()
                .authenticationEntryPoint(new AuthenticationEntryPointException())
                .accessDeniedHandler(new AccessDeniendHandlerException())
                .and()
                .authorizeRequests()
                .antMatchers("/login/**").permitAll()
                .antMatchers("/js/**","/css/**","/images/**").permitAll()
                .anyRequest()
                .authenticated();
    }
}
